<template>
  <div>
    <el-upload
      :class="{ disabled: disabled }"
      action="#"
      list-type="picture-card"
      :file-list="fileList"
      :on-preview="handlePictureCardPreview"
      :limit="limit"
      :on-remove="handleRemove"
      :http-request="handleUpload"
      :on-change="handleChange"
      :before-upload="beforeAvatarUpload"
    >
      <i class="el-icon-plus" />
      <div class="delImg">
        <i  class="el-icon-circle-close"></i>
      </div>
    </el-upload>

    <!-- 进度条（cos有自带的进度条 所以这里这个不用） -->
    <!-- <el-progress
      class="progress"
      :text-inside="true"
      :stroke-width="26"
      :percentage="percent"
      style="width:40%"
    /> -->

    <!-- 预览 -->
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>

  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
import { nanoid } from 'nanoid'

const cos = new COS({
  SecretId: 'AKIDAGGPH6lKn9LTWRF1rdHkYLyX3UpzwgJn',
  SecretKey: 'SksnU3dAbv5BPXZSJ9xHdzNivbAYu12x'
})

export default {
  name: 'ImageUpload',
  props: {
    limit: {
      type: Number,
      default: 1
    }
  },
  data () {
    return {
      fileList: [],
      dialogImageUrl: '',
      dialogVisible: false,
      percent: 100
    }
  },
  computed: {
    disabled () {
      return this.fileList.length >= this.limit
    },
    isAllUploadSuccess () {
      return this.fileList.every(item => item.status === 'success')
    }
  },
  methods: {
    // 预览
    handlePictureCardPreview (file) {
      this.dialogImageUrl = file.url
      // console.log(file.url)
      this.dialogVisible = true

      return file.url
    },
    // 删除
    handleRemove (file, fileList) {
      // console.log(file, fileList)
      this.fileList = this.fileList.filter(item => item.uid !== file.uid)
    },
    // 上传文件之前的钩子 给图片加验证规则
    beforeAvatarUpload (file) {
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
        return false
      }
      return true
    },
    // 添加
    handleUpload (obj) {
      // console.log('添加', obj)
      const fileObj = this.fileList.find(item => item.uid === obj.file.uid)

      // 进度条
      fileObj.status = 'uploading'

      cos.putObject({
        Bucket: 'hrsass-gcy-1312315726', /* 填入您自己的存储桶，必须字段 */
        Region: 'ap-shanghai', /* 存储桶所在地域，例如ap-beijing，必须字段 */
        Key: nanoid() + obj.file.name, /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */
        StorageClass: 'STANDARD',
        Body: obj.file, // 要上传文件对象
        onProgress: (progressData) => {
          // console.log(JSON.stringify(progressData))

          fileObj.percentage = parseInt(progressData.percent * 100)
          // this.percent = parseInt(progressData.percent * 100)
        }
      }, (err, data) => {
        if (err) {
          console.log(err)
          return
        }
        // console.log(data)
        fileObj.url = 'http://' + data.Location

        // 如果太快就让他等1秒
        setTimeout(() => {
          fileObj.status = 'success'
        }, 1000)
      })
    },
    // 文件状态改变时的钩子
    handleChange (file, fileList) {
      // 深拷贝arr
      function copyArr (arr) {
        const res = []
        for (let i = 0; i < arr.length; i++) {
          res.push(arr[i])
        }
        return res
      }
      const res = copyArr(fileList)
      const json = JSON.stringify(res)
      this.$emit('update:imgUrl', json)
      // console.log(json)
      // this.$emit('update:imgUrl', json)
      // console.log(res)
      // console.log(res[0].url)
      // console.log(this.fileList)
      // // const res = fileList[0]
      // console.log(this.fileList[0].url)
      this.fileList = [...fileList]
      // console.log(file)
    }
  }
}
</script>

<style lang="scss" scoped>
/* @import url(); 引入css类 */
.disabled {
  ::v-deep {
    .el-upload--picture-card {
      display: none;
    }
  }

}
.progress{
  ::v-deep{
    .el-progress-bar__inner{
      line-height: 0;
    }
  }
}
::v-deep {
  .el-upload-list--picture-card .el-upload-list__item  {
    position: absolute;
    top: -10px;
    left: 280px;
    width: 100px;
    height: 60px;
    width: 100px;
    height: 60px;
  }
  .el-upload--picture-card {
    position: absolute;
    top: -10px;
    left: 280px;
    width: 100px;
    height: 60px;
  }
  .el-icon-plus{
    // background-color: #8df;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }
}
.delImg {
  position: absolute;
  top: -10px;
  right: 5px;
  width: 5px;
  height: 5px;
  background: #fff;
  border-radius: 50%;
  text-align: center;
  line-height: 20px;
  color: #333;
  cursor: pointer;
}
</style>
